@{
    ViewData["Title"] = "消息中心";
    Layout = "_Layout";
}

<div class="container-fluid mt-4">
    <!-- 聊天容器 -->
    <div class="row">
        <!-- 左侧联系人列表 -->
        <div class="col-md-3">
            <div class="card h-100">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">联系人</h5>
                </div>
                <div class="list-group list-group-flush" id="contactList">
                    <!-- 联系人会动态加载 -->
                </div>
            </div>
        </div>

        <!-- 右侧聊天区域 -->
        <div class="col-md-9">
            <div class="card h-100 d-flex flex-column">
                <!-- 聊天标题栏 -->
                <div class="card-header bg-light d-flex justify-content-between align-items-center">
                    <h5 class="mb-0" id="currentChatTitle">请选择一个联系人开始聊天</h5>
                    <span id="connectionStatus" class="badge bg-secondary">未连接</span>
                </div>

                <!-- 消息显示区域 -->
                <div class="card-body flex-grow-1 overflow-auto p-0" id="messageContainer">
                    <div class="text-center text-muted mt-5">
                        <i class="fas fa-comments fa-3x mb-3"></i>
                        <p>选择一个联系人开始对话</p>
                    </div>
                </div>

                <!-- 输入区域 -->
                <div class="card-footer border-top p-3" id="inputArea" style="display: none;">
                    <div class="form-group mb-2">
                        <textarea id="messageInput" class="form-control" rows="3" placeholder="输入消息..."></textarea>
                    </div>
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted" id="typingIndicator"></small>
                        <button id="sendButton" class="btn btn-primary">
                            <i class="fas fa-paper-plane"></i> 发送
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        // 全局变量
        let ws = null;
        let currentContact = null;
        let contacts = [
            { id: "product", name: "吴维昊", unread: 0 },
            { id: "product_duan", name: "段栋兴", unread: 0 },
            { id: "product_zhao", name: "赵舒雅", unread: 0 },
            { id: "product_zhang", name: "张可欣", unread: 0 },
            { id: "product_wang", name: "王雨龙", unread: 0 }
        ];

        // DOM元素
        const contactList = document.getElementById('contactList');
        const messageContainer = document.getElementById('messageContainer');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const currentChatTitle = document.getElementById('currentChatTitle');
        const connectionStatus = document.getElementById('connectionStatus');
        const inputArea = document.getElementById('inputArea');
        const typingIndicator = document.getElementById('typingIndicator');

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            renderContacts();
            connectWebSocket();

            // 发送消息
            sendButton.addEventListener('click', sendMessage);
            messageInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                } else if (currentContact) {
                    // 发送正在输入状态
                    sendTypingStatus();
                }
            });
        });

        // 渲染联系人列表
        function renderContacts() {
            contactList.innerHTML = '';
            contacts.forEach(contact => {
                const contactItem = document.createElement('a');
                contactItem.href = '#';
                contactItem.className = `list-group-item list-group-item-action d-flex justify-content-between align-items-center ${currentContact === contact.id ? 'active' : ''}`;

                let unreadBadge = '';
                if (contact.unread > 0) {
                    unreadBadge = `<span class="badge bg-primary rounded-pill">${contact.unread}</span>`;
                }

                contactItem.innerHTML = `
                    <div>
                        <div class="fw-bold">${contact.name}</div>
                        <small class="text-muted">点击开始聊天</small>
                    </div>
                    ${unreadBadge}
                `;

                contactItem.addEventListener('click', function(e) {
                    e.preventDefault();
                    selectContact(contact.id, contact.name);
                });

                contactList.appendChild(contactItem);
            });
        }

                function selectContact(contactId, contactName) {
            currentContact = contactId;
            currentChatTitle.textContent = contactName;
            inputArea.style.display = 'block';
            messageInput.focus();

            // 重置未读消息数
            const contact = contacts.find(c => c.id === contactId);
            if (contact && contact.unread > 0) {
                contact.unread = 0;
                renderContacts();
            }

            // 加载历史消息（实际项目中应从API获取）
            loadChatHistory(contactId);

            // 选择联系人后再连接WebSocket
            connectWebSocket();
        }

        // 连接WebSocket
        function connectWebSocket() {
            // 先关闭可能存在的旧连接
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.close();
            }
            try {
                const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
                const host = window.location.host;
                // 此时currentChatTitle.textContent是有效的联系人名称
                const url = `ws://localhost:5104/api/RabbitMqContinuousMonitor/MonitorQueue?queueName=${encodeURIComponent(currentContact)}`;

                ws = new WebSocket(url);

                ws.onopen = function() {
                    console.log('WebSocket连接已建立');
                    connectionStatus.className = 'badge bg-success';
                    connectionStatus.textContent = '已连接';
                };

                ws.onmessage = function(event) {
                    handleMessage(event.data);
                };

                ws.onclose = function() {
                    console.log('WebSocket连接已关闭');
                    connectionStatus.className = 'badge bg-warning';
                    connectionStatus.textContent = '已断开';

                    // 自动重连
                    setTimeout(connectWebSocket, 3000);
                };

                ws.onerror = function(error) {
                    console.error('WebSocket错误:', error);
                    connectionStatus.className = 'badge bg-danger';
                    connectionStatus.textContent = '连接错误';
                };
            } catch (error) {
                console.error('连接失败:', error);
                setTimeout(connectWebSocket, 3000);
            }
        }

        // 处理接收到的消息
        function handleMessage(data) {
            try {
                const message = JSON.parse(data);

                // 区分消息类型：队列状态（status）、实际消息（message）、错误（error）
                switch(message.MessageType) {
                    case "message":
                        // 后端推送的消息格式：QueueMessage对象，Content是序列化后的聊天内容
                        const chatContent = JSON.parse(message.Content); // 解析消息内容
                        // 构建前端显示的消息结构
                        const displayMessage = {
                            type: "message",
                            target: message.QueueName, // 目标队列=联系人ID
                            content: chatContent.Content, // 实际聊天内容
                            sender: chatContent.Sender, // 发送者（如“我”或对方名称）
                            timestamp: chatContent.SendTime, // 发送时间
                            isSelf: chatContent.Sender === "我", // 是否是自己发送的
                            messageId: chatContent.MessageId
                        };
                        addMessageToChat(displayMessage);
                        break;
                    case "status":
                        // 队列状态信息（可选：显示队列当前消息数等）
                        console.log("队列状态：", message);
                        // 示例：显示队列消息数更新
                        // showSystemMessage(`队列 ${message.QueueName} 消息数：${message.MessageCount}`);
                        break;
                    case "error":
                        showSystemMessage("错误：" + message.Error);
                        break;
                }
            } catch (error) {
                console.error("解析消息失败:", error);
                showSystemMessage("收到无效消息格式：" + error.message);
            }
        }

        // 发送消息
        function sendMessage() {
                const content = messageInput.value.trim();
        if (!content || !currentContact || !ws || ws.readyState !== WebSocket.OPEN) {
            alert("请先选择联系人并确保连接正常！");
            return;
        }


        // 1. 构建消息数据（目标队列=联系人ID，发送者=“我”）
        const messageData = {
            TargetQueue: currentContact, // 目标队列对应联系人ID（如“product_duan”）
            SenderName: "我",
            Content: content
        };

        // 2. 调用后端接口将消息写入队列
        fetch("http://localhost:5104/api/RabbitMqContinuousMonitor/SendMessageToQueue", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                // 如果有身份验证，需要添加Token头（如JWT）
                // "Authorization": "Bearer " + localStorage.getItem("token")
            },
            body: JSON.stringify(messageData)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error("消息发送失败，状态码：" + response.status);
            }
            return response.json();
        })
        .then(data => {
            if (data.Success) {
                // 3. 写入成功后，前端显示自己的消息
                const localMessage = {
                    type: "message",
                    target: currentContact,
                    content: content,
                    sender: "我",
                    timestamp: new Date().toISOString(),
                    isSelf: true,
                    messageId: data.MessageId
                };
                addMessageToChat(localMessage);
                messageInput.value = ""; // 清空输入框
            } else {
                throw new Error(data.Message || "消息发送失败");
            }
        })
        .catch(error => {
            console.error("发送消息出错：", error);
            showSystemMessage("消息发送失败：" + error.message);
        });
        }

        // 发送正在输入状态
        function sendTypingStatus() {
            if (!currentContact || !ws || ws.readyState !== WebSocket.OPEN) {
                return;
            }

            const typingMsg = {
                type: 'typing',
                target: currentContact
            };

            ws.send(JSON.stringify(typingMsg));
        }

        // 发送命令
        function sendCommand(command, data) {
            const cmd = {
                type: 'command',
                command: command,
                data: data
            };

            ws.send(JSON.stringify(cmd));
        }

        // 添加消息到聊天界面
        function addMessageToChat(message) {
            // 如果消息不是当前聊天对象的，更新未读计数
            if (message.target !== currentContact && !message.isSelf) {
                const contact = contacts.find(c => c.id === message.target);
                if (contact) {
                    contact.unread++;
                    renderContacts();
                    return;
                }
            }

            // 清空正在输入提示
            typingIndicator.textContent = '';

            const messageDiv = document.createElement('div');
            messageDiv.className = `p-3 ${message.isSelf ? 'text-end' : 'text-start'}`;

            const senderName = message.isSelf ? '我' : getContactName(message.sender);
            const messageBubbleClass = message.isSelf
                ? 'bg-primary text-white float-end'
                : 'bg-light text-dark float-start';

            messageDiv.innerHTML = `
                <div class="d-inline-block max-w-75">
                    <small class="text-muted d-block ${message.isSelf ? 'text-right' : ''}">${senderName}</small>
                    <div class="p-2 rounded ${messageBubbleClass} mb-1">${formatMessageContent(message.content)}</div>
                    <small class="text-muted d-block ${message.isSelf ? 'text-right' : ''}">${formatTime(message.timestamp)}</small>
                </div>
                <div class="clearfix"></div>
            `;

            messageContainer.appendChild(messageDiv);
            scrollToBottom();
        }

        // 显示系统消息
        function showSystemMessage(content) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'p-3 text-center';
            messageDiv.innerHTML = `
                <span class="text-muted small bg-light px-3 py-1 rounded-pill">${content}</span>
            `;

            messageContainer.appendChild(messageDiv);
            scrollToBottom();
        }

        // 显示正在输入提示
        function showTypingIndicator(senderId) {
            if (currentContact !== senderId) return;

            const senderName = getContactName(senderId);
            typingIndicator.textContent = `${senderName} 正在输入...`;

            // 5秒后清除提示
            setTimeout(() => {
                if (typingIndicator.textContent.includes(senderName)) {
                    typingIndicator.textContent = '';
                }
            }, 5000);
        }

        // 加载聊天历史
        function loadChatHistory(contactId) {
            // 实际项目中应从API获取历史消息
            messageContainer.innerHTML = '';
            showSystemMessage(`开始与 ${getContactName(contactId)} 聊天`);
        }

        // 辅助函数：获取联系人名称
        function getContactName(contactId) {
            const contact = contacts.find(c => c.id === contactId);
            return contact ? contact.name : '未知用户';
        }

        // 辅助函数：格式化时间
        function formatTime(timestamp) {
            const date = new Date(timestamp);
            return date.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 辅助函数：格式化消息内容
        function formatMessageContent(content) {
            // 简单处理换行
            return content.replace(/\n/g, '<br>');
        }

        // 滚动到底部
        function scrollToBottom() {
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }
    </script>
}
